# ========================
# Makefile for CloudFS Project
# 优化目录结构 & 依赖管理
# ========================

# ------------
# 编译器配置
# ------------
CC = gcc
CFLAGS = -Wall -Wextra -I. -g -MMD -MP  # 启用严格警告 & 自动生成依赖
LDFLAGS = -L/usr/lib/mysql -lmysqlclient  # MySQL 库链接[6,7](@ref)

# ------------
# 目录结构定义
# ------------
BIN_DIR = bin
OBJ_DIR = obj
USER_FILES_DIR = $(BIN_DIR)/user_files
CLIENT_SRC_DIR = client
SERVER_SRC_DIR = server

# ------------
# 目标文件定义
# ------------
CLIENT_TARGET = $(BIN_DIR)/cloudfs_client
SERVER_TARGET = $(BIN_DIR)/cloudfs_server

# ------------
# 源文件配置
# ------------
CLIENT_SRCS = $(wildcard $(CLIENT_SRC_DIR)/*.c)
SERVER_SRCS = $(wildcard $(SERVER_SRC_DIR)/*.c)

CLIENT_OBJS = $(patsubst $(CLIENT_SRC_DIR)/%.c,$(OBJ_DIR)/client_%.o,$(CLIENT_SRCS))
SERVER_OBJS = $(patsubst $(SERVER_SRC_DIR)/%.c,$(OBJ_DIR)/server_%.o,$(SERVER_SRCS))

# ------------
# 编译配置
# ------------
CLIENT_CFLAGS = $(CFLAGS) -DBUFFER_SIZE=512   # 客户端缓冲区[1](@ref)
SERVER_CFLAGS = $(CFLAGS) -DPATH_MAX=4096      # 服务端路径长度[3](@ref)

# ------------
# 主构建目标
# ------------
all: init client server
	@echo "✅ 项目编译完成！可执行文件位于 $(BIN_DIR)"

# ------------
# 初始化目录
# ------------
init:
	@mkdir -p $(BIN_DIR) $(USER_FILES_DIR) $(OBJ_DIR)
	@echo "📂 目录结构初始化完成"

# ------------
# 客户端构建
# ------------
client: $(CLIENT_TARGET)

$(CLIENT_TARGET): $(CLIENT_OBJS)
	$(CC) $(CLIENT_CFLAGS) -o $@ $^ $(LDFLAGS)
	@echo "🖥️ 客户端编译完成: $@"

# ------------
# 服务端构建
# ------------
server: $(SERVER_TARGET)

$(SERVER_TARGET): $(SERVER_OBJS)
	$(CC) $(SERVER_CFLAGS) -o $@ $^ $(LDFLAGS)
	@echo "🖥️ 服务端编译完成: $@"

# ------------
# 模式规则 (统一处理.c->.o编译)
# ------------
$(OBJ_DIR)/client_%.o: $(CLIENT_SRC_DIR)/%.c
	$(CC) $(CLIENT_CFLAGS) -c $< -o $@

$(OBJ_DIR)/server_%.o: $(SERVER_SRC_DIR)/%.c
	$(CC) $(SERVER_CFLAGS) -c $< -o $@

# ------------
# 清理与运行
# ------------
clean:
	rm -rf $(OBJ_DIR)/*.o $(OBJ_DIR)/*.d
	@echo "🧹 清理所有对象文件"

distclean: clean
	rm -f $(CLIENT_TARGET) $(SERVER_TARGET)
	rm -rf $(USER_FILES_DIR)/*
	@echo "🧹 彻底清理可执行文件及用户数据"

run-server: server
	@echo "🚀 启动云存储服务端..."
	@$(SERVER_TARGET)

# ------------
# 依赖管理
# ------------
-include $(wildcard $(OBJ_DIR)/*.d)

# ------------
# 伪目标声明
# ------------
.PHONY: all init client server clean distclean run-server